import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

/**
 * 
 */

/**
 * @author inaki_torres
 *
 */
public class GestionTareasBD implements GestionTareas {
	private Connection con;
	private Statement stat;
	public GestionTareasBD(){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			con=DriverManager.getConnection("jdbc:mysql://localhost/Tareas","root","");
			stat = con.createStatement();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}
	/* (non-Javadoc)
	 * @see GestionTareas#introducirTarea(java.lang.String)
	 */
	@Override
	public int introducirTarea(String tarea) {
		String insertQuery="insert into Tareas (Tarea) values('"+tarea+"')";
		int result=0;
		try {
			result=stat.executeUpdate(insertQuery,Statement.RETURN_GENERATED_KEYS);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see GestionTareas#eliminarTarea(int)
	 */
	@Override
	public void eliminarTarea(int id) {
		String insertQuery="delete * from Tareas where id="+id;
		try {
			stat.executeUpdate(insertQuery);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/* (non-Javadoc)
	 * @see GestionTareas#modificarTarea(Tarea)
	 */
	@Override
	public void modificarTarea(Tarea tarea) {
		String insertQuery="update Tareas set Tarea='"+tarea.getTarea()+"' where id="+tarea.getId();
		try {
			stat.executeUpdate(insertQuery);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/* (non-Javadoc)
	 * @see GestionTareas#buscarTarea(int)
	 */
	@Override
	public Tarea buscarTarea(int id){
		Tarea tarea;
		String insertQuery="select Tareas.* from Tareas where id="+id;
		ResultSet resultset;
		try {
			resultset = stat.executeQuery(insertQuery);
		
			if (resultset.next()){
				int iden=resultset.getInt("Id");
				String tare=resultset.getString("Tarea");
				tarea=new Tarea(iden,tare);
				return tarea;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see GestionTareas#listaTareas()
	 */
	@Override
	public Vector<Tarea> listaTareas() {
		Vector<Tarea> listatareas=new Vector<Tarea>();
		String insertQuery="insert * from Tareas";
		ResultSet resultset;
		try {
			resultset = stat.executeQuery(insertQuery);
			while (resultset.next()) {
				int id=resultset.getInt("id");
				String tarea=resultset.getString("Tarea");
				listatareas.add(new Tarea(id,tarea));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listatareas;
	}

}
